﻿$.Jahanutility = {}
$(function () {
    $.extend($.Jahanutility, {

        getParameterByName: function (name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        },

        //=======================================================
        //start : to fill a drop down by data
        fillDrp: function (elem, serviceUrl, inData, topic, ID) {
            $.ajax({
                url: serviceUrl,
                data: inData,
                'async': false,
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data['d'] != null) {
                        if (data['d'].length == 0) {
                            $.kish.message.getErrorMessage("15");
                        }
                        else {

                            for (var i = 0; i < data['d'].length; i++) {
                                var x = '<option value="' + data['d'][i].ID + '">' + data['d'][i].Code + '</option>';
                                $(elem).append(x);
                            }
                            if (topic)
                                $(elem).prepend("<option value=0 selected='selected'>" + topic + "</option>");

                            if (ID != undefined) {
                                $(elem).val(ID)
                            }
                        }
                    }
                }
            });
        },
        //end : to fill a drop down by data


        //=======================================================
        //start : to fill a table by one dimentional table
        fillTable: function (table, serviceUrl, Header, delUrl, UpdateUrl, delWarnCode, inData) {
            $.ajax({
                url: serviceUrl,
                data: inData,
                'async': false,
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {

                    if (data['d'] != null && data['d'].length != 0) {
                        var tableHeader = '<tr><th class="width150">' + Header + '</th><th class="width40">ویرایش</th><th class="width40">حذف</th></tr>';
                        table.append(tableHeader);
                        var delClass = "del_" + $.Jahanutility.GUID();
                        var addClass = "add_" + $.Jahanutility.GUID();
                        for (var i = 0; i < data['d'].length; i++) {
                            var x = '<tr id=' + data['d'][i].ID + '>'
                            + '<td ><span class="dataSpan">' + $.trim(data['d'][i].Code) + ' </span> <input type="text" class="display_none validaion inputData" /></td >'
                                + '<td><img alt="ویرایش" title="ویرایش" class="noBorder  inline-block pointer fn_edit " src="../../Images/ico/edit.gif" />'
                                    + '<img alt="ذخیره" title="ذخیره" class="noBorder display_none pointer fn_add right ' + addClass + '" src="../../Images/ico/tick.png" />'
                                    + '<img alt="لغو" title="لغو" class="noBorder display_none pointer fn_cancel right" src="../../Images/ico/close.png" /></td>'
                                + '<td><img alt="حذف" title="حذف" src="../../Images/ico/delete.gif" class="noBorder inline-block pointer fn_del ' + delClass + '" /></td>'
                              + '</tr>';
                            table.append(x);
                        };

                        $('.' + delClass).click(function () {
                            var thisRow = $(this).closest("tr");
                            $.Jahanutility.DelObject(thisRow, delUrl, delWarnCode);
                        });

                        $('.fn_cancel').click(function () {
                            var thisRow = $(this).closest("tr");
                            $.Jahanutility.ShowTrElem(thisRow);
                        });

                        $('.fn_edit').click(function () {
                            var thisRow = $(this).closest("tr");
                            $.Jahanutility.EditableTr(thisRow);
                        });

                        $('.' + addClass).click(function () {
                            var thisRow = $(this).closest("tr");
                            $.Jahanutility.UpdateObject(thisRow, UpdateUrl);
                        });
                    }
                }
            });
        },
        //end :  to fill a table by one dimentional table


        //=======================================================
        DelObject: function (thisRow, url, msgCode) {
            var ObjectToDelID = thisRow.attr('id');
            $.kish.message.getConfirmationMessage(msgCode, function () {
                $.ajax({
                    'type': 'POST',
                    'url': url,
                    'data': JSON.stringify({ "ID": ObjectToDelID }),
                    'contentType': 'application/json; charset=utf-8',
                    'dataType': 'json',
                    'success': function (result) {
                        if (result['d'].IsSucceed) {
                            $(thisRow).remove();
                            //$.kish.message.showUserMessage(result['d'].Message.Message);
                        }
                        else {
                            $.kish.message.showErrorMessage(result['d'].Message.Message);
                        }
                    },
                    'error': function () {
                        $.kish.message.alertError("خطا در سیستم");
                    }
                });

            }, function () {
                // $this.show();
            });
        },

        //=======================================================
        EditableTr: function (thisRow) {
            var codeSpan = thisRow.find('.dataSpan');
            var data = codeSpan.html();
            thisRow.find('.inputData').val(data);
            codeSpan.hide();
            thisRow.find('.fn_edit').hide();
            thisRow.find('.display_none').each(function () {
                $(this).slideDown();
            });
        },

        //=======================================================
        UpdateObject: function (thisRow, url) {
            var UpOjb = {};
            var ObjectToUpID = thisRow.attr('id');
            var data = $.trim(thisRow.find('.inputData').val());
            var lastData = thisRow.find('.dataSpan').html();
            if (!data)
                return false;
            if (lastData == data)
                $.Jahanutility.ShowTrElem(thisRow, data);
            UpOjb.ID = ObjectToUpID;
            UpOjb.Code = data;
            $.ajax({
                'type': 'POST',
                'url': url,
                'data': JSON.stringify({ "DTO": UpOjb }),
                'contentType': 'application/json; charset=utf-8',
                'dataType': 'json',
                'success': function (result) {
                    if (result['d'].IsSucceed) {
                        $.Jahanutility.ShowTrElem(thisRow, data);
                    }
                    else {
                        $.kish.message.showErrorMessage(result['d'].Message.Message);
                    }
                },
                'error': function () {
                    $.kish.message.alertError("خطا در سیستم");
                }
            });

        },

        //=======================================================
        ShowTrElem: function (thisRow, data) {
            thisRow.find('.display_none').each(function () {
                $(this).hide();
            });
            thisRow.find('.fn_edit').slideDown();
            var spanElem = thisRow.find('.dataSpan');
            if (data)
                spanElem.html(data);
            spanElem.slideDown();

        },
        //**********************************************************

        GUID: function () {
            return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
        },


        //**********************************************************
        togglePanels: function (btn, elem, firtOpen) {

            if (firtOpen) {
                btn.toggle(function () {
                    // run the first time
                    elem.slideDown();
                }, function () { // run the second time
                    elem.slideUp();
                });
            }
            else {
                btn.toggle(function () {
                    // run the first time
                    elem.slideUp();
                }, function () { // run the second time
                    elem.slideDown();
                });
            }

        }
    });
});


//**********************************************************
$(document).ready(function () {
    $('.chkSelectAll').click(function () {
        $('.chk').attr('checked', this.checked);
    });
    $(".chk").click(function () {

        if ($(".chk").length == $(".chk:checked").length) {
            $(".chkSelectAll").attr("checked", "checked");
        } else {
            $(".chkSelectAll").removeAttr("checked");
        }

    });
});
